package com.tai.cobrapp.activity.crud;

import com.tai.cobrapp.R;
import com.tai.cobrapp.activity.AdminPanelActivity;
import com.tai.cobrapp.activity.LoginActivity;
import com.tai.cobrapp.activity.OptionsMenuActivity;
import com.tai.cobrapp.adapter.EditEstablishmentListAdapter;
import com.tai.cobrapp.backend.Backend;
import com.tai.cobrapp.model.Establecimiento;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;

public class EditEstablishmentsActivity extends ListActivity{
	
	private final static int EDIT_ESTABLISHMENT_DIALOG = 1;
	private final static int EDIT_ESTABLISHMENT_ITEM_DIALOG = 2;
	private final static int YA_EXISTE_ESTABLECIMIENTO = 3;
	private final static int COMPLETE_CAMPO_NAME = 4;
	private final static int ESTABLECIMIENTO_GUARDADO = 5;

	EditEstablishmentListAdapter adapter = null;
	Establecimiento establecItem = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_surveys);

		adapter = new EditEstablishmentListAdapter(this, Backend.getInstance().getEstablecimientos(null, this.getListView().getContext()));
		this.getListView().setAdapter(adapter);
		
		this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// Agregar Custom Dialog para pedir lo necesario del dispositivo, luego cambiar los colores del item, vendido o no, etc
				//detalleAuxiliar = ((DetalleRelevamiento)adapter.getItem(position));
				//detalleListPosition = position;
				establecItem = (Establecimiento)adapter.getItem(position);
				
				showDialog(EDIT_ESTABLISHMENT_DIALOG);
				return false;
			}
		});
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialogo;
		Dialog dialogoEditEstab;
		
		switch(id){
		case EDIT_ESTABLISHMENT_DIALOG:
			dialogo = new Dialog(this);
			dialogo.setContentView(R.layout.edit_establishment_dialog);
			dialogo.setTitle(R.string.establishment_options);
			
			android.view.WindowManager.LayoutParams params = dialogo.getWindow().getAttributes();
			params.width = LayoutParams.MATCH_PARENT;
			params.height = LayoutParams.MATCH_PARENT;
			dialogo.getWindow().setAttributes(params);

			Button editEstabBtn = (Button)dialogo.findViewById(R.id.edit_estab_item_btn);
			Button editDevicesBtn = (Button)dialogo.findViewById(R.id.edit_devices_btn);
			Button deleteEstabBtn = (Button)dialogo.findViewById(R.id.delete_estab_item_btn);
			Button cancelBtn = (Button)dialogo.findViewById(R.id.cancel_estab_btn);
			//final CheckBox fueVendido = (CheckBox)dialogo.findViewById(R.id.fue_vendido_chkbox);
//			Context _this = this;
			android.view.View.OnClickListener editEstabListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_ESTABLISHMENT_DIALOG);
					showDialog(EDIT_ESTABLISHMENT_ITEM_DIALOG);
				}
			};
			
			android.view.View.OnClickListener editarDevicesListener = new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i = new Intent(EditEstablishmentsActivity.this, EditDevicesActivity.class);
					i.putExtra("idEstablecimiento", establecItem.getId());
					startActivity(i);
				}
			};
			android.view.View.OnClickListener deleteEstabListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_ESTABLISHMENT_DIALOG);
					AlertDialog.Builder builder = new AlertDialog.Builder(EditEstablishmentsActivity.this);
			        builder.setMessage(R.string.sure_change_state)
			               .setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
			                   public void onClick(DialogInterface dialog, int id) {
			                	   // borrar el establecimiento
			                	   establecItem.setActive(!establecItem.isActive());
			                	   actualizarEstablecimiento(establecItem);
			                	   adapter.notifyDataSetChanged();
			                   }
			               })
			               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			                   public void onClick(DialogInterface dialog, int id) {
			                       // User cancelled the dialog
			                   }
			               });
			        builder.create().show();
				}
			};
			
			android.view.View.OnClickListener cancelarListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_ESTABLISHMENT_DIALOG);
				}
			};
			
			editEstabBtn.setOnClickListener(editEstabListener);
			editDevicesBtn.setOnClickListener(editarDevicesListener);
			deleteEstabBtn.setOnClickListener(deleteEstabListener);
			cancelBtn.setOnClickListener(cancelarListener);
			return dialogo;
		case EDIT_ESTABLISHMENT_ITEM_DIALOG:
			dialogoEditEstab = new Dialog(this);
			dialogoEditEstab.setContentView(R.layout.edit_establish_or_device_item_dialog);
			dialogoEditEstab.setTitle(R.string.edit_establishment);
			
			android.view.WindowManager.LayoutParams paramsEditItem = dialogoEditEstab.getWindow().getAttributes();
			paramsEditItem.width = LayoutParams.MATCH_PARENT;
			paramsEditItem.height = LayoutParams.MATCH_PARENT;
			dialogoEditEstab.getWindow().setAttributes(paramsEditItem);
			
			final EditText estabEditName = (EditText)dialogoEditEstab.findViewById(R.id.name);
			final EditText estabEditDesc = (EditText)dialogoEditEstab.findViewById(R.id.description);
			Button saveEstabEditBtn = (Button)dialogoEditEstab.findViewById(R.id.save_btn);
			Button cancelEstabEditBtn = (Button)dialogoEditEstab.findViewById(R.id.cancel_btn);
			
			estabEditName.setText(establecItem.getName());
			estabEditDesc.setText(establecItem.getDescription());
			
			android.view.View.OnClickListener saveEstabItemListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(estabEditName.getText().toString() == null || estabEditName.getText().toString().isEmpty() ){
						warningMessage(COMPLETE_CAMPO_NAME, null);
						return;
					}else if(existeOtroEst(establecItem.getName(), estabEditName.getText())){
						warningMessage(YA_EXISTE_ESTABLECIMIENTO, estabEditName.getText().toString());
						estabEditName.setText("");
						return;
					}else{
						establecItem.setName(estabEditName.getText());
						establecItem.setDescription(estabEditDesc.getText());
						actualizarEstablecimiento(establecItem);
						adapter.notifyDataSetChanged();
						warningMessage(ESTABLECIMIENTO_GUARDADO, estabEditName.getText().toString());
						dismissDialog(EDIT_ESTABLISHMENT_ITEM_DIALOG);
					}
				}
			};
			android.view.View.OnClickListener cancelEstabItemListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_ESTABLISHMENT_ITEM_DIALOG);
				}
			};
			
			saveEstabEditBtn.setOnClickListener(saveEstabItemListener);
			cancelEstabEditBtn.setOnClickListener(cancelEstabItemListener);
			return dialogoEditEstab;
		default:
			return super.onCreateDialog(id);
		}
		
	}
	private void warningMessage(Integer message, String name){
		switch (message) {
		case COMPLETE_CAMPO_NAME:
			Toast.makeText(this, this.getString(R.string.fields_incomplete) + ": " + this.getString(R.string.name), Toast.LENGTH_SHORT).show();
			break;
		case YA_EXISTE_ESTABLECIMIENTO:
			Toast.makeText(this, name + " " + this.getString(R.string.establishment_already_exists), Toast.LENGTH_SHORT).show();
			break;
		case ESTABLECIMIENTO_GUARDADO:
			Toast.makeText(this, this.getString(R.string.establishment_edited_successful) + ": " + name, Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
	}
	public boolean existeOtroEst(Editable nombreBase, Editable establishment){
		return Backend.getInstance().existeOtroEstablecimiento(this, nombreBase, establishment);
	}
	private void actualizarEstablecimiento(Establecimiento establ){
		Backend.getInstance().updateEstablishment(this, establecItem);
	}
	@Override
	public void onBackPressed() {
		Intent i = new Intent(EditEstablishmentsActivity.this, AdminPanelActivity.class);
		startActivity(i);
		super.onBackPressed();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	@Override
	protected void onStop() {
		finish();
		super.onStop();
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case R.id.main_menu:
			Intent i = new Intent(this, OptionsMenuActivity.class);
			startActivity(i);
			break;
		case R.id.log_out:
			Intent i2 = new Intent(this, LoginActivity.class);
			startActivity(i2);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
